<?php
/**
 * Created by PhpStorm.
 * User: MrHung
 * Date: 1/22/14
 * Time: 5:27 PM
 */

namespace Api\Controller;


use Admin\Model\AdminUser;
use Velacolib\Utility\Utility;
use Zend\Authentication\AuthenticationService;
use Zend\Form\Element;
use Zend\Mvc\Controller\AbstractActionController;

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');

class LoginController extends AbstractActionController
{

    public function onDispatch(\Zend\Mvc\MvcEvent $e)
    {
        $this->layout('frontend/layout');
        return parent::onDispatch($e);
    }

    public function indexAction()
    {
    }

    public function loginAction()
    {

        $aut = new AuthenticationService();
        if ($aut->hasIdentity() == 1) {
            $response['result'] = false;
            $response['message'] = 'Bạn đang đã đăng nhập rồi';
            $response['isLogin'] = true;
            //return $this->redirect()->toRoute('home', array('action' => 'index'));
        }
        $response['result'] = false;

        //$response['locate'] = '';		
        if ($this->getRequest()->isPost()) {

            $data = $this->params()->fromPost();

            $user_table = Utility::UserGateway('Admin\Model\AdminUserTable');

            $user_table->setLoginUser($data);

            $login_obj = new AuthenticationService(null, $user_table);

            $login_obj->authenticate();

            //$test = new AuthenticationService();
            //echo '<pre>';
            ///print_r($login_obj->getIdentity());die;

            if ($login_obj->hasIdentity() == 1) {
                if ($login_obj->getIdentity()->confirm == 0) {
                    $response['isLogin'] = false;
                    $response['result'] = false;
                    $response['message'] = 'Bạn chưa xác nhận tài khoản qua email ....';
                    $response['email'] = $login_obj->getIdentity()->email;
                    $response['time_reg'] = $login_obj->getIdentity()->time_reg;
                    $response['name'] = $login_obj->getIdentity()->name;
                    $response['confirm'] = 0;
                } else {
                    $response['result'] = true;

                    $response['message'] = 'Đăng nhập thành công ....!';

                    // $response['locate'] = 'http://' . $_SERVER['HTTP_HOST'];
                }
            } else {

                $response['result'] = false;

                $response['message'] = 'Sai Tên đăng nhập hoặc mật khẩu, vui lòng thử lại!';

            }
            header("ContentType: application/json");

            echo json_encode($response);
            die();
        }
    }

    /*
     * forgot pass
     * $email =  $_post['email']
     * */

    public function authEmailForgotAction()
    {
        $request = $this->getRequest();
        $email = $_POST['email'];
        $userModel = Utility::UserGateway("Admin\Model\AdminUserTable");
        $user = $userModel->getUserByEmail($email);

        if ($email == $user->email) {
            $pass = time();
            $newpass = md5($user->email . $pass);
            $user->password = $newpass;
            $userModel->saveUser($user);
            //sending email recover password to user
            $smtp_option = null;
            $senderInfo = array(
                'email' => 'admin@vela.com',
                'name' => 'Vela Corp'

            );

            $RecipientInfo = array(
                'email' => $user->email,
                'name' => $user->name,
                'password' => $pass,
            );

            $template_path = 'admin/email/tpl/forgotpass';

            $subject = 'Vela Recover password';

            Utility::SendMail(false, $smtp_option = null, $senderInfo, $RecipientInfo, $template_path, $subject);


            $response['result'] = true;
            $response['message'] = "New password has been send to your email! please checked!";
        } else {
            $response['result'] = false;
            $response['message'] = "Email không hợp lệ";
        }
        echo json_encode($response);
        die;

    }

    public function isloginAction()
    {
        $aut = new AuthenticationService();
        if ($aut->hasIdentity() == 1) {
            $response['result'] = true;
            $response['message'] = 'Bạn đang đã đăng nhập rồi';
            $response['isLogin'] = true;

        }
        echo json_encode($response);
        die();
    }

    /*
     * login fb api app
     * */

    public function fbloginAction()
    {
        $request = $this->getRequest();
        if($request->isPost()){
            $data = $this->params()->fromPost();

            $email = $data['email'];
            $id = $data['fbId'];

            $fb_picture = "https://graph.facebook.com/".$id."/picture";
            $userTalbe = new AdminUser();
            $userModel = Utility::UserGateway("Admin\Model\AdminUserTable");
            // check true /false email
            $user =  $userModel->getUserByEmail($email);
            $aut = new AuthenticationService();
            if ($aut->hasIdentity() == 1) {
                $response['result'] = false;
                $response['message'] = 'Bạn đang đã đăng nhập rồi';
                $response['isLogin'] = true;
                //return $this->redirect()->toRoute('home', array('action' => 'index'));
            }else{
                if(is_object($user)){
                    $response['result'] = true;
                    $response['message'] = 'Đăng nhập thành công';
                    $response['locate'] = 'http://' . $_SERVER['HTTP_HOST'];
                    $user =  $userModel->getUserByEmail($email);
                    $response['user_info'] = $user;
                    echo json_encode($response);die;
                }else{
                    $user_save = array(
                        'name' => $email,
                        'email' => $email,
                        'avatar' => $fb_picture,
                        'time_reg'=>time(),
                        'user_type'=>2,
                        'confirm'=>1
                    );

                    $userTalbe->exchangeArray($user_save);
                    $userModel->saveUser($userTalbe);
                    // authenticate
                    $login_user['username'] = $user_save['email'];
                    $userModel->setLoginUser($login_user);
                    $login_obj = new AuthenticationService(null, $userModel);
                    $login_obj->authenticate();
                    $response['result'] = true;
                    $response['message'] = 'Đăng nhập thành công';
                    $response['locate'] = 'http://' . $_SERVER['HTTP_HOST'];
                    $user =  $userModel->getUserByEmail($email);
                    $response['user_info'] = $user;
                    echo json_encode($response);die;

                }
            }
        }
//        md5($data_reg['email'].$data_reg['password']);
        die;


    }
} 